+server.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import auth from "$lib/server/auth.js";
  2. import Recipe from "$lib/server/models/Recipe.js";
  3. import {error, json} from "@sveltejs/kit";
  4. export async function POST({request, cookies, params}){
  5. const user = await auth(cookies, false);
  6. const body = await request.json();
  7. if(!body.name) error(400, "Recipe name required");
  8. if(body.ingredients.length <= 0) error(400, "Ingredients required");
  9. if(body.steps.length <= 0) error(400, "Preparation steps required");
  10. for(let i = 0; i < body.ingredients.length; i++){
  11. if(body.ingredients[i].quantity <= 0) error(400, "Quantity must be greater than 0");
  12. if(!body.ingredients[i].name) error(400, "Ingredient name required");
  13. }
  14. const recipe = await Recipe.findOne({_id: params.recipeId});
  15. recipe.name = body.name;
  16. recipe.ingredients = body.ingredients;
  17. recipe.steps = body.steps;
  18. recipe.notes = body.notes;
  19. recipe.private = body.private;
  20. recipe.updatedAt = new Date();
  21. await recipe.save();
  22. return json({msg: "success"}, {status: 200});
  23. }
  24. export async function DELETE({cookies, params}){
  25. const user = await auth(cookies, false);
  26. let recipe;
  27. try{
  28. recipe = await Recipe.findOne({_id: params.recipeId});
  29. if(!recipe || user._id.toString() !== recipe.user.toString()) error(403, "Forbidden");
  30. await Recipe.deleteOne({_id: params.recipeId});
  31. }catch(e){
  32. if(e.status === 403) error(403, "Forbidden");
  33. error(500, "Internal Server Error");
  34. }
  35. return json({msg: "success"}, {status: 200});
  36. }